import {isEmpty,showToast} from '@/utils/index.js'
export default{
	data(){
		return {
			downloadTask:null,
			downloading:false
		}
	},
	methods:{
		preview(path) {
			if(isEmpty(path)){
				showToast('没有文件可预览')
				return;
			}
			//#ifdef APP-PLUS
			//检查文件是否已经存在
			//标记为在打开文件
			uni.setStorageSync('previewLoading',true);
			const filename = path.substring(path.lastIndexOf("/") + 1);
			plus.io.resolveLocalFileSystemURL(
				`_downloads/${filename}`,
				(entry) => { //本地存在
					this.openLocalFile(entry.toLocalURL())
					//this.startDownload(path, filename)
				}, (e) => { //本地不存在
					this.startDownload(path, filename)
				});
			//#endif
		},
		//插件打开本地文件
		openLocalFile(filePath) {
			// uni.showLoading({
			// 	title: "文件加载中...",
			// 	mask:true
			// });
			//plus.os.name
			if (plus.os.name == 'Android') {
				setTimeout(function(){
					uni.setStorageSync('previewLoading',false);
					uni.hideLoading();
				},1500);
				const openOffice = uni.requireNativePlugin("FUN-OfficeViewer");
				openOffice.openfile(plus.io.convertLocalFileSystemURL(filePath));
			} else if (plus.os.name == 'iOS') {
				uni.openDocument({
					filePath: filePath,
					complete:function(){
						console.log('close')
						setTimeout(function(){
							uni.setStorageSync('previewLoading',false);
							uni.hideLoading();
						},200);
					}
				})
			}
		},
		//下载文件
		startDownload(path, filename) {
			this.downloading = true;
			uni.showLoading({
				title: "文件加载中...",
				mask:true
			});
			this.downloadTask = plus.downloader.createDownload(path, {
				filename: `_downloads/${filename}`
			}, (d, status) => { //下载完成
				//uni.hideLoading();
				this.downloading = false;
				if (d.state==4 
				//&& status == 200
				) {
					this.openLocalFile(d.filename)
				} else {
					showToast('下载失败')
				}
			});
			this.downloadTask.start(); //开始下载   
		},
		//终止下载任务
		abort(){
			if(this.downloadTask){
				this.downloadTask.abort();
			}
		},
		isDownloading(){
			return this.downloading
		}
	}
}